import { Graph } from '@antv/x6';
import { Stencil } from '@antv/x6-plugin-stencil';
import { DataItem, convertDataList, outputDataList, inputDataList } from './data';

// 注册组件面板
export function createStencil(graph: Graph, stencilContainer: HTMLElement) {
  const stencil = new Stencil({
    title: '组件面板',
    target: graph,
    stencilGraphWidth: 300,
    stencilGraphHeight: 180,
    search(cell, keyword) {
      return cell.attr('text/text').includes(keyword);
    },
    collapsable: true,
    groups: [
      {
        title: '输入',
        name: 'inputPanel',
        graphHeight: 0,
        layoutOptions: {
          rowHeight: 70,
        },
      },
      {
        title: '输出',
        name: 'outPanel',
        graphHeight: 0,
        layoutOptions: {
          rowHeight: 70,
        },
      },
      {
        title: '转换组件',
        name: 'convertPanel',
        graphHeight: 0,
        layoutOptions: {
          rowHeight: 70,
        },
      },
    ],
    layoutOptions: {
      columns: 1,
      columnWidth: 150,
      rowHeight: 55,
      /*resizeToFit: true,*/
    },
  });
  stencilContainer!.appendChild(stencil.container);
  createStencilNode(graph, convertDataList, stencil, 'convertPanel');
  createStencilNode(graph, inputDataList, stencil, 'inputPanel');
  createStencilNode(graph, outputDataList, stencil, 'outPanel');
  return stencil;
}

function createStencilNode(
  graph: Graph,
  dataList: DataItem[],
  stencil: Stencil,
  groupName: string,
) {
  const nodes = dataList.map((item) =>
    graph.createNode({
      shape: 'custom-rect-image',
      label: item.label,
      data: item.path,
      attrs: {
        image: {
          'xlink:href': item.image,
        },
      },
      ports: {
        items: [
          {
            group: 'right',
          },
          {
            group: 'left',
          },
        ],
      },
    }),
  );
  stencil.load(nodes, groupName);
}
